package com.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

/**
 * 公众平台通用接口工具类
 *
 * @author
 * @date 2013-08-09
 */
public class HttpConnectUtil {

	private static Log log = LogFactory.getLog( HttpConnectUtil.class);

	// 京东万象 appkey
	public static final String JDappKey = "e09683fb0036894d9fffe4e8a836137d";
	//聚合appkey
	public static final String JHappKey = "b450b8bbd09d6b949554fceeffe91007";
//	public static final String JHappKey = "7427005ba4f5186c4f556df19eaadfeb";
	//百度图片搜索地址
	public static final String IMG_URL_BAIDU="https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&fm=index&pos=history&word=";
	//360图片搜索地址
	public static final String IMG_URL_360="http://m.image.so.com/i?q=";
	//万年历接口地址
	public static final String RequestUrl_WNL2="http://v.juhe.cn/calendar/month?";
	//特殊替换符
	public static final String FH_1="#SHI#LEI#";

	public static Map<String,List<String>> map= new HashMap();
//

	// private static Logger log = LoggerFactory.getLogger(HttpConnectUtil.class);

	/**
	 * 发起https请求并获取结果
	 *
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
		String result = null;
		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

			// 设置通用的请求属性
			httpUrlConn.setRequestProperty("accept", "*/*");
			httpUrlConn.setRequestProperty("connection", "Keep-Alive");
			httpUrlConn.setRequestProperty("Charset", "utf-8");

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			result = buffer.toString();

			System.out.println(result );

		} catch (ConnectException ce) {
			log.error("Weixin server connection timed out.");
		} catch (Exception e) {
			log.error("https request error:{}", e);
		}
		return result;
	}

	// 图灵机器人
	public static String tuLing(String info, String loc, String userid) {
		String requestUrl = "https://way.jd.com/turing/turing?";
		String requestMethod = "POST";
		String outputStr = "info=" + info
				+ "&loc=" + loc
				+ "&userid=" + userid
				+ "&appkey=" + JDappKey;
		System.out.println("url:--" + outputStr);
		String jsonMessage = httpRequest(requestUrl, requestMethod, outputStr);
		String result = "";

		//去掉非分隔符的冒号
		jsonMessage=removeColonForJson(jsonMessage);
		// 将json转成map
		Map maps = (Map) JSON.parse(jsonMessage);
		Map resultMap = (Map) maps.get("result");


		String temp = (String) resultMap.get("text");
		String url = (String) resultMap.get("url");
		System.out.println(temp);
		if (temp != null) {
			result = temp;
		}
		if(url!=null) {
			url="<a href=\""+url+"\">打开页面</a>";
			url=url.replace("http //", "http://");
			url=url.replace(IMG_URL_360, IMG_URL_BAIDU);
			result+=url;
		}
		return result;
	}

	// 图灵机器人2
	public static Map<String, String> tuLing2(String info, String loc, String userid) {
		String requestUrl = "https://way.jd.com/turing/turing?";
		String requestMethod = "POST";
		String outputStr = "info=" + info
				+ "&loc=" + loc
				+ "&userid=" + userid
				+ "&appkey=" + JDappKey;
		System.out.println("url:--" + outputStr);
		String jsonMessage = httpRequest(requestUrl, requestMethod, outputStr);
		String result = "";

		//去掉非分隔符的冒号
		jsonMessage=removeColonForJson(jsonMessage);
		// 将json转成map
		Map maps = (Map) JSON.parse(jsonMessage);
		Map resultMap = (Map) maps.get("result");


//		String temp = (String) resultMap.get("text");
//		System.out.println(temp);
//		if (temp != null) {
//			result = temp;
//		}
		return resultMap;
	}
	//菜谱大全
	public static String caiPu(String keyword, int num) {
		String requestUrl = "https://way.jd.com/jisuapi/search?";
		String requestMethod = "POST";
		String outputStr = "keyword=" + keyword
				+ "&num=" + num
				+ "&appkey=" + JDappKey;
		log.info(outputStr);
		String jsonMessage = httpRequest(requestUrl, requestMethod, outputStr);
		String result = "";

		//去掉非分隔符的冒号
		jsonMessage=removeColonForJson(jsonMessage);

		log.info(jsonMessage);

		// 将json转成map
		Map maps = (Map) JSON.parse(jsonMessage);
		Map resultMap = (Map) maps.get("result");


		String temp = (String) resultMap.get("text");

		log.info(temp);

		if (temp != null) {
			result = temp;
		}
		return result;
	}
	//
	public static String removeColonForJson(String str) {
		if (str==null) {
			return null;
		}
//		return str.replace("\":", FH_1).replace(":", " ").replace(FH_1, "\":");
		return str;
	}


	/**
	 * 获取假日信息和调休信息
	 * @return map：
	 * key1 holidays
	 * key2 weekdays
	 */
	public static Map<String, List<String>> getHolidaysAndWeekdays(String date) {
		String requestUrl = RequestUrl_WNL2;
		String requestMethod = "POST";
		String outputStr = "year-month="+date + "&key=" + JHappKey;

		log.info(outputStr);
		String jsonMessage = httpRequest(requestUrl, requestMethod, outputStr);


		//去掉非分隔符的冒号
		//jsonMessage=removeColonForJson(jsonMessage);


		JSONObject jsonObject = JSONObject.parseObject(jsonMessage);

		List<String> holidays = new ArrayList<>();
		List<String> weekdays = new ArrayList<>();
		String strReason = (String) jsonObject.get("reason");
		JSONObject resultJObj = (JSONObject)jsonObject.get("result");
		JSONObject dataJObj = (JSONObject) resultJObj.get("data");

		String strHoliday = (String) dataJObj.get("holiday");
		JSONArray holidayArr = JSONObject.parseArray(strHoliday);
		for (Object o : holidayArr) {
			JSONObject holiday = (JSONObject) o;
			JSONArray list = (JSONArray) holiday.get("list");
			for (Object o1 : list) {
				JSONObject day = (JSONObject) o1;
				String strDate = (String) day.get("date");
				String status = (String) day.get("status");
				System.out.println(strDate+"==="+status);
				if (status=="1"){
					holidays.add(strDate);
				}
				if (status=="2"){
					weekdays.add(strDate);
				}
			}
		}
		Map<String, List<String>> holidayWeekdaysMap = new HashMap<>();
		holidayWeekdaysMap.put("holidays",holidays);
		holidayWeekdaysMap.put("weekdays",weekdays);


		List<String> holidays1 = map.get("holidays");
		if (holidays1!=null){
			holidays.addAll(holidays1);
		}
		List<String> weekdays1 = map.get("weekdays");
		if (holidays1!=null){
			weekdays.addAll(weekdays1);
		}
		map.put("holidays",holidays);
		map.put("weekdays",weekdays);

		return holidayWeekdaysMap;
	}

	public static boolean isWeekday(@NotNull String date){
		int i = date.lastIndexOf("-");
		String mouthDate=date.substring(0,i);
		List<String> holidays = map.get("holidays");
		List<String> weekdays = map.get("weekdays");
		for (String holiday : holidays) {
			if (holiday.equals(date)){
				return false;
			}
		}
		for (String weekday : weekdays) {
			if (weekday.equals(date)){
				return true;
			}
		}
		String weekOfDate = getWeekOfDate(date);
		if ("星期日".equals(weekOfDate)||"星期六".equals(weekOfDate)){
			return false;
		}
		return true;
	}

	public static String getWeekOfDate(Date dt) {
		String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);

		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		return weekDays[w];
	}

	public static String getWeekOfDate(String date){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date dt = null;
		try {
			dt = dateFormat.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		return weekDays[w];
	}

	/**
	 * 获取指定月份的天数
	 * @param year
	 * @param month
	 * @return
	 */
	public static int getDaysByYearMonth(int year, int month) {

		Calendar a = Calendar.getInstance();
		a.set(Calendar.YEAR, year);
		a.set(Calendar.MONTH, month - 1);
		a.set(Calendar.DATE, 1);
		a.roll(Calendar.DATE, -1);
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}

	/**
	 * 遍历一个月的所有日期
	 * @param year
	 * @param month
	 */
	public static List<String> dayReport(int year,int month) {

		List<String> dateList = new ArrayList<>();
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR,year);//month 为指定月份任意日期
		cal.set(Calendar.MONTH,month-1);
		int dayNumOfMonth = getDaysByYearMonth(year, month);
		cal.set(Calendar.DAY_OF_MONTH, 1);// 从一号开始

		for (int i = 0; i < dayNumOfMonth; i++, cal.add(Calendar.DATE, 1)) {
			Date d = cal.getTime();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-M-d");
			String df = simpleDateFormat.format(d);
			dateList.add(df);
		}
		return dateList;
	}

	public static void main(String[] args) {
		for (int i = 2; i < 12; i+=3) {
			System.out.println(i);
			String date="2018-"+i;
			System.out.println(date);
			getHolidaysAndWeekdays(date);
		}
//		List<String> holidays = map.get("holidays");
//		for (String holiday : holidays) {
//			System.out.println(holiday);
//		}
	}

}
